<?php

namespace app\index\controller;

use think\Controller;
use think\Session;
use think\Db;
use phpmailer\phpmailer;

class Login extends Controller {

    public function _initialize() {
        parent::_initialize();
    }

    public function index() {
        $data = Db::name('member')->find(Session::get('member_info.id'));
        return $this->fetch('', ['data' => $data]);
    }

    //会员登录
    public function login() {
        if ($this->request->isPost()) {
            $post = input('post.');
            $validate_result = $this->validate($post, 'Login');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                $where['account'] = $post['account'];
                $where['password'] = md5($post['password']);

                $member = Db::name('member')->where($where)->find();

                if (!empty($member)) {
                    Session::delete('no_login');
                    Session::set('member_info', $member);
                    $this->success('Login success', url('index/account'));
                } else {
                    $this->error('<div style="text-align:left">The username or password you entered is incorrect.<br/><br/><a href='.url('login/reg').'>New user.</a><br/><br/><a href="#register" data-toggle="modal" id="click">Forget password.</a></div>');
                }
            }
        }
    }

    /* 会员注册 */

    public function reg() {
        $page = input('param.page') ? input('param.page') : '';
        if ($this->request->isPost()) {
            $post = input('post.');
            switch ($page) {
                case 'reg':
                    $validate_result = $this->validate($post, 'Reg.reg');

                    if ($validate_result !== true) {
                        $this->error($validate_result);
                    } else {
                        unset($post['page']);
                        Session::set('info', $post);
                        $this->success('Processing......', url('login/reg', ['page' => 'reg1']));
                    }
                    break;
                case 'reg2':
                    if (!Session::get('info'))
                        $this->error('Please register according to regular procedure！');

                    $validate_result = $this->validate($post, 'Reg.reg2');

                    if ($validate_result !== true) {
                        $this->error($validate_result);
                    } else {
                        unset($post['page']);
                        Session::set('info', array_merge(Session::get('info'), $post));
                        $this->success('Processing......', url('login/reg', ['page' => 'reg2']));
                    }
                    break;
                case 'reg3':
                    if (!Session::get('info'))
                        $this->error('Please register according to regular procedure！');

                    $validate_result = $this->validate($post, 'Reg.reg3');

                    if ($validate_result !== true) {
                        $this->error($validate_result);
                    } else {
                        unset($post['page']);
                        $post['is_default'] = 1;
                        Session::set('addr', $post);
                        $this->success('Processing......', url('login/reg', ['page' => 'reg3']));
                    }
                    break;
                case 'reg4':
                    if (!Session::get('info'))
                        $this->error('Please register according to regular procedure！');

                    $validate_result = $this->validate($post, 'Reg.reg4');

                    if ($validate_result !== true) {
                        $this->error($validate_result);
                    } else {
                        unset($post['page']);
                        Session::set('info', array_merge(Session::get('info'), $post));
                        $this->success('Processing......', url('login/reg', ['page' => 'reg4']));
                    }
                    break;
                case 'reg5':
                    if (!Session::get('info'))
                        $this->error('Please register according to regular procedure！');

                    $validate_result = $this->validate($post, 'Reg.reg5');

                    if ($validate_result !== true) {
                        $this->error($validate_result);
                    } else {
                        unset($post['page']);
                        unset($post['config_password']);
                        Session::set('info', array_merge(Session::get('info'), $post));

                        Session::set('info.add_time', time()); //注册时间
                        Session::set('info.password', md5(Session::get('info.password')));  //密码加密

                        Db::startTrans();
                        try {
                            Db::name('member')->insert(Session::get('info'));
                            $member_id = Db::name('member')->getLastInsID();

                            Session::set('info.id', $member_id);
                            Session::set('addr.member_id', $member_id);

                            Db::name('member_addr')->insert(Session::get('addr'));
                            // 提交事务
                            Db::commit();
                        } catch (\Exception $e) {
                            // 回滚事务
                            Db::rollback();
                            $this->error($e->getMessage());
                        }
                        Session::set('member_info', Db::name('member')->find(Session::get('info.id')));
                        Session::delete('addr');  //注册的地址信息
                        
                        $level_id = Session::get('info.level_id');  //获取用户选择的等级
                        
                        Session::delete('info');  //注册的信息
                        Session::delete('no_login'); //未登录标识 如果存在那么也删除
                        
                        $this->success('Congratulations! You have successfully registered.', ($level_id !=1) ? url('index/pay') : url('index/account'));
                    }
                    break;
            }
        }

        if ($page == 'reg1') {
            $this->assign('member_level', cache('member_level'));
        }

//        p(Session::get());
        return $this->fetch($page);
    }

    /* email */

    public function email() {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            
            $result = $this->validate($data, 'Reg.reg6');

            $info = Db::name('member')->where(['email'=>$data['email']])->find();
            if(!$info)
                $this->error('Non Registered User！');
            
            if (true !== $result) {
                $this->error($result);
            } else {
                
                $mail = new PHPMailer(); //实例化
                $mail->IsSMTP(); // 启用SMTP
                $mail->Host = "smtp.exmail.qq.com"; //SMTP服务器 以163邮箱为例子
                $mail->Port = 25;  //邮件发送端口
                $mail->SMTPAuth = true;  //启用SMTP认证

                $mail->CharSet = "UTF-8"; //字符集
                $mail->Encoding = "base64"; //编码方式

                $mail->Username = "info@fcpai.org";  //你的邮箱
                $mail->Password = "Hk123456";  //你的密码
                $mail->Subject = "你好"; //邮件标题

                $mail->From = "info@fcpai.org";  //发件人地址（也就是你的邮箱）
                $mail->FromName = "fcpai";  //发件人姓名

                $address = $data['email']; //收件人email
                $mail->AddAddress($address, "亲"); //添加收件人（地址，昵称）

                $mail->IsHTML(true); //支持html格式内容
                $mail->Body = '<h2>Dear '.$info['prefix'].$info['surnames'].$info['first_name'].$info['middle_name'].',</h2><br/>We have received your password request. Please follow the link below to reset your password:<br/><a href='.$this->request->domain().url('login/pass',[urlencode(base64_encode('mid'))=>  base64_encode($info['id'])]).'>click here</a><br/><br/><p>Thank you</p>'; //邮件主体内容
                //发送
                if (!$mail->Send()) {
                    $this->error('Failed to send');
                } else {
                    $this->success('Thank you for your request!<br/>An email was sent to '.$data['email'].'  with instructions to change your password.');
                }
            }
        }
    }
    
    /*修改密码*/
    public function pass () {
        
        if($this->request->isPost()){
            $data = input('post.');
            $result = $this->validate($data, 'Reg.reg7');
            
            if (true !== $result) {
                $this->error($result);
            } else {
                $status = Db::name('member')->update(['password'=>md5($data['password']),'id'=>$data['id']]);
                if ($status!==false) {
                    Session::clear();
                    Session::destroy();
                    $this->success('The password has changed successfully. Please sign in again', url('login/index'));
                } else {
                    $this->error('Password modification failed');
                }
            }
        }
        
        
        $data = input('param.');
        
        if(!isset($data[urlencode(base64_encode('mid'))])){
            $data['msg'] = 'Illegal operation！';
        }else{
            $data['info'] = Db::name('member')->find(base64_decode($data[urlencode(base64_encode('mid'))]));
        }
        
        return $this->fetch('',['data'=>$data]);
        
    }
    

    //会员退出
    public function loginout() {
        Session::clear();
        Session::destroy();
        $this->success('Exiting login...', url('login/index'));
    }

    /* 异步通知 */

    public function notify() {

        if ($this->request->isPost()) {
            // 由于该URL不仅仅只有Paypal的服务器能访问，其他任何服务器都可以向该方法发起请求。
            // 所以要判断请求发起的合法性，也就是要判断请求是否是paypal官方服务器发起的 
            // 拼凑 post 请求数据 
//            $req = 'cmd=_notify-validate';// 验证请求  
//            foreach ($_POST as $k=>$v)  
//            {  
//                $v = urlencode(stripslashes($v));  
//                $req .= "&{$k}={$v}";  
//            }
//            
//            $ch = curl_init('https://ipnpb.sandbox.paypal.com/cgi-bin/webscr');
////            $ch = curl_init('https://www.paypal.com/cgi-bin/webscr');
//            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//            curl_setopt($ch, CURLOPT_POST, 1);
//            curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
//            $res = curl_exec($ch);
//            curl_close($ch);
//            file_put_contents('44.php', $res);
//            if ($res) {
//                file_put_contents('1.php', $res);
            // 本次请求是否由Paypal官方的服务器发出的请求 
//                if (strcmp($res, 'VERIFIED') == 0) {
//                
            //判断订单的状态    不知道什么原应 反正paypal总是返回空  干脆自己验证  
            if (isset($_POST['payment_status']) && $_POST['payment_status'] == 'Completed') {

                $invoice = decrypt($_POST['invoice'], 'zhuzong520*'); // 得到自己定义的订单号

                if (substr($invoice, 0, 2) !== 'hj') {  //如果不是宏景的订单那么out
                    exit('fail');
                }

                $item_name1 = $_POST['item_name']; //购买的项目名称
                $payment_status = $_POST['payment_status'];
                $payment_currency = $_POST['mc_currency'];
                $txn_id = $_POST['txn_id'];
                $receiver_email = $_POST['receiver_email'];
                $payer_email = $_POST['payer_email'];
                $mc_gross = $_POST['mc_gross']; // 付款金额  
                $custom = $_POST['custom']; // 自定义参数  1标识续费  

                $array = explode('|', $invoice);

                $level_name = $array[2];
                $member_id = $array[1];
                $order_id = $array[0];

                $expire_time = strtotime("+1 year");  //正常情况下是加一年

                if ($custom && $custom == 1) {  //如果是续费 那么查出该会员的最后记录加上一年
                    $info2 = Db::name('member_pay_log')->where(['member_id' => $member_id])->order('expire_time desc')->find();
                    $expire_time = strtotime("+1 year", $info2['expire_time']);
                }

                $data = [
                    'member_id' => (int) $member_id,
                    'currency' => $payment_currency,
                    'txn_id' => $txn_id,
                    'order_id' => $order_id,
                    'gross' => $mc_gross,
                    'pay_time' => time(),
                    'expire_time' => $expire_time,
                    'level' => $level_name,
                ];

                //会员id
                $level_id = 1;
                $member_level = cache('member_level');
                foreach ($member_level as $k => $v) {
                    if ($v['level_name'] == $level_name) {
                        $level_id = $v['level'];
                    }
                }

                $info = Db::name('member_pay_log')->where(['order_id' => $order_id])->find();

                if (!$info) {
                    DB::transaction(function () use ($data, $member_id, $level_id) {
                        db('member_pay_log')->insert($data);
                        db('member')->where(['id' => $member_id])->update(['pay_status' => 1, 'level_status' => 1, 'level_id' => $level_id]);
                    });
                }
            }
        } else {// 如果有任意一项成立，则终止执行。由于是给机器看的，所以不用考虑什么页面。直接输出即可 
            exit('fail');
        }
//                } else {
//                    exit('fail');
//                }
//            }
//            // read the post from PayPal system and add 'cmd'  
//            $req = 'cmd=_notify-validate';
//
//            foreach ($_POST as $key => $value) {
//                $value = urlencode(stripslashes($value));
//                $req .= "&$key=$value";
//            }
//
//            // post back to PayPal system to validate  
//            $header = '';
//            $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
//            $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
//            $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
//
//            $fp = fsockopen('https://ipnpb.paypal.com/cgi-bin/webscr', 443, $errno, $errstr, 30); // 沙盒用  
//            //$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30); // 正式用  
//            // assign posted variables to local variables  
//
//            $invoice = $_POST['invoice']; // 得到自己定义的订单号
//            $item_name1 = $_POST['item_name1']; //购买的项目名称
//            $payment_status = $_POST['payment_status'];
//            $payment_currency = $_POST['mc_currency'];
//            $txn_id = $_POST['txn_id'];
//            $receiver_email = $_POST['receiver_email'];
//            $payer_email = $_POST['payer_email'];
//            $mc_gross = $_POST['mc_gross']; // 付款金额  
//            $custom = $_POST['custom']; // 自定义参数  1标识续费  
//
//            if(isset($payment_status) && $payment_status =='Completed'){
//                
//            }
//        }
    }

}
